package com.ydler.file.controller;


import ccom.ydles.entity.Result;
import ccom.ydles.entity.StatusCode;
import com.ydler.file.util.FastDFSClient;
import com.ydler.file.util.FastDFSFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {


    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    public Result result(MultipartFile file){
        try {
            String name = file.getName();//不对，这是form表单的name
            String originalFilename = file.getOriginalFilename();//这才是文件名
            //文件内容
            byte[] bytes = file.getBytes();//字节数组
            //文件拓展名
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1);// .jpg2
            //FastDFSFile
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,bytes,ext);
            //调用工具类真正上传
            String[] upload = FastDFSClient.upload(fastDFSFile); //group1/MOO/OO/OOWALHFLAsga/SFS.JPG
            //拿到图片路径，访问该url可以直接看到图片
            String url = FastDFSClient.getTrackerUrl() + upload[0]+"/"+upload[1];

            return new Result(true, StatusCode.OK,StatusCode.SUCCESS,url);
        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR,StatusCode.FAIL);
        }

    }
}
